<?php
header("Content-Type: application/json; charset=UTF-8");
require_once 'db.php';

// 获取POST数据
$user_id = isset($_POST['user_id']) ? intval($_POST['user_id']) : 0;
$old_password = isset($_POST['old_password']) ? trim($_POST['old_password']) : '';
$new_password = isset($_POST['new_password']) ? trim($_POST['new_password']) : '';

// 参数验证
if ($user_id <= 0 || empty($old_password) || empty($new_password)) {
    echo json_encode([
        'status' => 'error',
        'message' => '参数错误'
    ]);
    exit;
}

try {
    // 验证原密码
    $check_sql = "SELECT password FROM users WHERE id = ?";
    $check_stmt = $conn->prepare($check_sql);
    if (!$check_stmt) {
        throw new Exception("预处理语句创建失败");
    }
    
    $check_stmt->bind_param("i", $user_id);
    if (!$check_stmt->execute()) {
        throw new Exception("查询执行失败");
    }
    
    $result = $check_stmt->get_result();
    if ($result->num_rows === 0) {
        throw new Exception("用户不存在");
    }

    $user = $result->fetch_assoc();
    
    // 验证原密码是否正确
    if (!password_verify($old_password, $user['password'])) {
        throw new Exception("原密码错误");
    }

    // 生成新密码的哈希值
    $new_password_hash = password_hash($new_password, PASSWORD_DEFAULT);
    
    // 更新密码
    $update_sql = "UPDATE users SET password = ? WHERE id = ?";
    $update_stmt = $conn->prepare($update_sql);
    if (!$update_stmt) {
        throw new Exception("预处理语句创建失败");
    }
    
    $update_stmt->bind_param("si", $new_password_hash, $user_id);
    if (!$update_stmt->execute()) {
        throw new Exception("更新密码失败");
    }

    if ($update_stmt->affected_rows > 0) {
        echo json_encode([
            'status' => 'success',
            'message' => '密码修改成功'
        ]);
    } else {
        throw new Exception("密码未更新");
    }

} catch (Exception $e) {
    echo json_encode([
        'status' => 'error',
        'message' => $e->getMessage()
    ]);
} finally {
    if (isset($check_stmt)) $check_stmt->close();
    if (isset($update_stmt)) $update_stmt->close();
    $conn->close();
}
?> 